package utils

import (
	"context"
	"fmt"
	"github.com/sirupsen/logrus"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"time"
)

func CreatePod(clientset *kubernetes.Clientset, pod *v1.Pod, namespace string, log *logrus.Logger) (*v1.Pod, error) {
	log.Info("Creating Pod...")
	createdPod, err := clientset.CoreV1().Pods(namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
	if err != nil {
		log.Errorf("Failed to create Pod: %v", err)
		return nil, err
	}
	log.Infof("Created Pod: %s", createdPod.Name)
	return createdPod, nil
}

func DeletePod(clientset *kubernetes.Clientset, podName, namespace string, log *logrus.Logger) error {
	log.Info("Deleting Pod...")
	err := clientset.CoreV1().Pods(namespace).Delete(context.TODO(), podName, metav1.DeleteOptions{})
	if err != nil {
		log.Errorf("Failed to delete Pod: %v", err)
		return err
	}
	log.Info("Pod deleted")
	return nil
}

func WaitForPodPhase(clientSet *kubernetes.Clientset, podName, namespace string, targetPhase v1.PodPhase, timeout time.Duration, log *logrus.Logger) error {
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	ticker := time.NewTicker(2 * time.Second) // 每两秒检查一次
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return fmt.Errorf("timeout waiting for Pod %s to reach phase %s: %w", podName, targetPhase, ctx.Err())
		case <-ticker.C:
			pod, err := clientSet.CoreV1().Pods(namespace).Get(ctx, podName, metav1.GetOptions{})
			if err != nil {
				log.Warnf("Error getting Pod %s status: %v", podName, targetPhase)
				continue
			}
			if pod.Status.Phase == targetPhase {
				return nil
			}
			log.Debugf("Pod %s current phase: %s, waiting for %s", podName, pod.Status.Phase, targetPhase)
		}
	}
}
